python shutil
复制文件和文件夹
import shutil, os
# 拷贝文件,并更改文件名
shutil.copy('data/hello1.txt', 'data/hello123.txt')
# 拷贝目录以及子目录所有文件
shutil.copytree('data', 'data_backup')
文件和文件夹的移动和改名
shutil.move('data/data.bak', 'data_backup')
shutil.move('data/data.bak', 'data_backup/data.bak.bak')
Warning
1、注意移动文件时,要判断目的地是文件夹还是文件。
2、目的地是文件会被覆盖。
3、如果对应目录不存在,则会报错。
永久删除文件和文件夹
#删除对应文件
os.unlink(path)
#删除文件夹。文件夹必须为空。
os.rmdir(path)
#删除PATH 文件夹,包括对应子目录。
shutil.rmtree(path)
遍历所有目录
import os
for floderName, subfolders, filenames in os.walk('C:\\Windows'):
print('The current folder is ' + floderName)
for subfolder in subfolders:
print('SUBFLODER OF ' + floderName + ': ' + subfolder)
for filename in filenames:
print('FILE INSIDEL ' + floderName + ': ' + filename)
print('')
ZIP 压缩文件处理
查看 ZIP 文件
import zipfile, os
os.chdir('D:\\') # move to the folder with example.zip
exampleZip = zipfile.ZipFile('CRT_LOG.zip')
print(exampleZip.namelist())
# View a file in the file list.
sapmInfo = exampleZip.getinfo('CRT_LOG/host192.168.10.111year2023mouth01day07port22hour_.log')
# Print one file Original size.
print(sapmInfo.file_size)
# Print compress_size .
print(sapmInfo.compress_size)
print(f"Compressed file is {round(sapmInfo.file_size / sapmInfo.compress_size, 2)}")
# Print compression ratio.
exampleZip.close()
解压缩 ZIP 文件
解压到当前目录
1、extractall 解压到当前目录。
import zipfile, os
os.chdir('D:\\') # move to the folder with example.zip
exampleZip = zipfile.ZipFile('CRT_LOG.zip')
# View a file in the file list.
print(exampleZip.namelist())
exampleZip.extractall()
exampleZip.close()
2、解压到指定目录
exampleZip. extractall ('D:\\CRT_LOG')
解压单个文件到指定目录
exampleZip. extract ('spam. txt')
'C:\\spam.txt'
exampleZip.extract('spam.txt', 'C:\\some\\new\\folders')
'C:\\some\\new\\folders\\spam.txt'
exampleZip.close()
创建和添加到 ZIP 文件
1、使用 ZipFile 函数传入' w' 参数。[1]
2、使用 write 方法第一个参数为文件名称。zipfile.ZIP_DEFLATED 这是一种压缩算法。[2]
import zipfile
os.chdir('D:\\') # move to the folder with example.zip
newZip = zipfile.ZipFile('new.zip','w')
newZip.write('CRT_LOG/', compress_type=zipfile.ZIP_DEFLATED)
newZip.close()
Warning
注意如果使用'w'选项,会擦除所有zip 文件内容。
如果只是希望添加文件,则需要传入'a'参数
zipfile.ZipFile('new.zip','a')
更改文件名日期格式
#! python3
# renameDates.py - Renames filenames with American MM-DD-YYY date format
# to European DD-MM-YYYY.
import shutil, os, re
# Create a regular expression to match the US date.
datePattern = re.compile(r"""^(.*?)
((19|20)\d\d)-
((0|1)?\d)-
((0|1|2|3)?\d)
(.*?)$
""", re.VERBOSE)
os.chdir('D:\\CRT_LOG')
# TODO: Loop over the files in the working directory.
for amerFilename in os.listdir('.'):
mo = datePattern.search(amerFilename)
if mo == None:
continue
# Get the different parts of the filename.
beforePart = mo.group(1)
monthPart = mo.group(2)
dayPart = mo.group(4)
yearPart = mo.group(6)
afterPart = mo.group(8)
euroFilename = beforePart + dayPart + '-' + monthPart + '-' + yearPart + afterPart
# TODO: Get the full, absolute file paths.
absWorkingDir = os.path.abspath('.')
amerFilename = os.path.join(absWorkingDir, amerFilename)
euroFilename = os.path.join(absWorkingDir, euroFilename)
# Rename the files.
print(f"Renameing {amerFilename} to {euroFilename}....")
shutil.move(amerFilename, euroFilename) # uncomment after testing
# TODO: Rename the files.
实践,自动更新所有 word 版本号
#! python3
# renameDates.py - Renames filenames with American MM-DD-YYY date format
# to European DD-MM-YYYY.
import shutil
import os
import re
# Create a regular expression to match the US date.
datePattern = re.compile(r"""^(.*?)
(v0\.)(\d\d)
(.*?)$
""", re.VERBOSE)
FileDir = 'D:\\03-R6课程置换-KCP'
os.chdir(FileDir)
# TODO: Loop over the files in the working directory.
for amerFilename in os.listdir('.'):
mo = datePattern.search(amerFilename)
if mo is None:
continue
# Get the different parts of the filename.
HeadFilename = mo.group(1)
Master_Version = mo.group(2)
Old_Version = int(mo.group(3))
New_Version = int(mo.group(3)) + 1
EndFilename = mo.group(4)
Old_Name = HeadFilename + Master_Version + str(Old_Version) + EndFilename
New_Name = HeadFilename + Master_Version + str(New_Version) + EndFilename
absWorkingDir = os.path.abspath('.')
oldFilename = os.path.join(absWorkingDir, Old_Name)
newFilename = os.path.join(absWorkingDir, New_Name)
# # Rename the files.
print(f"Renaming {oldFilename} to {newFilename}....")
shutil.move(oldFilename, newFilename) # uncomment after testing